<?php

namespace app\admin\model;

use think\Model;

use think\Db;
use think\Request;
use think\Exception;//事务处理

class Admin extends Model
{
    //获取所有用户相关数据
    public function getadmin($res)
    {
        $map = array();
        $admin = session('admin');
        if ($admin['position_id'] != 1) {
            //不是管理员只能看自己部门下的员工
            $defid = getinfo($admin['department_id'], 'department')['country_id'];
            $fid = array_column(getFrames('department', null, $defid), 'id');
            array_push($fid,$admin['department_id']);
            $map['a.department_id'] = ['in', $fid];
        }
        //状态查询 1在职 2 离职 3锁定
        if (isset($res['status']) && $res['status']) {
            $map['a.status'] = $res['status'];
        }
        //部门查询
        if (isset($res['department_id']) && $res['department_id']) {
            $map['a.department_id'] = $res['department_id'];
        }
        //职位查询
        if (isset($res['position_id']) && $res['position_id']) {
            $map['a.position_id'] = $res['position_id'];
        }
        //账号，昵称 姓名查询
        if (isset($res['dname']) && $res['dname']) {
            $maps['a.name'] = array('like', '%' . removeBlank($res['dname']) . '%');//账号
            $maps['a.nickname'] = array('like', '%' . removeBlank($res['dname']) . '%');//名称
            $maps['b.username'] = array('like', '%' . removeBlank($res['dname']) . '%');//姓名
        } else {
            $maps = array();
        }
        $datares = $this->alias('a')->join('nt_admin_info b', 'a.id=b.admin_id', 'left')->where(function ($query) use ($map) {
            $query->where($map);
        })->where(function ($query) use ($maps) {
            $query->whereOr($maps);
        })->field('a.*,b.firstname,b.lastname,b.birthday,b.remarks,b.sex,b.marry,b.wage,b.education,b.username')->order('a.create_at')->page($res['page'], $res['pageSize'])->select();
        $langs = $res['lang'];
        foreach ($datares as $datareskey => $datareval) {
            $datares[$datareskey]['update_date'] = getTimeDate($datareval['update_at'],12);
            if ($langs != 'zh') {
                //登录时间
                $datares[$datareskey]['login_date'] = getTimeDate($datareval['login_time'], 9);
                $datares[$datareskey]['create_date'] = getTimeDate($datareval['create_at'], 9);
                //入职时间
                $datares[$datareskey]['work_day_date'] = getTimeDate($datareval['work_day'], 8);
            } else {
                //登录时间
                $datares[$datareskey]['login_date'] = getTimeDate($datareval['login_time'],12);
                //入职时间
                $datares[$datareskey]['work_day_date'] = getTimeDate($datareval['work_day'], 7);
                $datares[$datareskey]['create_date'] = getTimeDate($datareval['create_at'], 12);
            }
            if ($admin['id'] == $datareval['id'] || $admin['position_id'] == 1) {
                $datares[$datareskey]['isedit'] = 1;
            } else {
                $datares[$datareskey]['isedit'] = 0;
            }
            //职位名称
            $rolewhere['mkey'] = 'position_' . $datareval['position_id'];
            $datares[$datareskey]['positionname'] = getlangname('multi_lang', $rolewhere, $langs);
            //部门名称
            $framewhere['mkey'] = 'department_' . $datareval['department_id'];
            $datares[$datareskey]['departmentname'] = getlangname('multi_lang', $framewhere, $langs);
            $datares[$datareskey]['sex'] = $this->getmanagelang($datareval['sex'], 1);//性别
            $datares[$datareskey]['langperson'] = $this->getmanagelang($datareval['language_id'], 2);//语言
            $datares[$datareskey]['mangname'] = getinfo($datareval['update_id'], 'admin')['nickname'];//编辑者
            $datares[$datareskey]['age'] = getTimeDate(null, 1) - getTimeDate($datareval['birthday'], 1); //年龄
        }
        $data['data'] = $datares;
        $data['ids'] = array_column($datares, 'id');
        $data['count'] = $this->alias('a')->join('nt_admin_info b', 'a.id=b.admin_id', 'left')->where(function ($query) use ($map) {
            $query->where($map);
        })->where(function ($query) use ($maps) {
            $query->whereOr($maps);
        })->count();
        return $data;
    }

    //获取对应用户的详情数据
    public function getxiangqin($res)
    {
        $langs = $res['lang'];//语言标志
        $infodata = $this->alias('a')->join('nt_admin_info b', 'a.id=b.admin_id', 'left')->field('a.*,b.firstname,b.lastname,b.birthday,b.remarks,b.sex,b.marry,b.wage,b.education,b.username')->where('a.id', $res['id'])->find();
        //部门名称
        $framewhere['mkey'] = 'department_' . $infodata['department_id'];
        $infodata['departmentname'] = getlangname('multi_lang', $framewhere, $langs);

        //职位名称
        $rolewhere['mkey'] = 'position_' . $infodata['position_id'];
        $infodata['positionname'] = getlangname('multi_lang', $rolewhere, $langs);
        $infodata['update_at'] = getTimeDate($infodata['update_at'],12);//更新时间
        if ($res['lang'] != 'zh') {
            $infodata['work_day_date'] = getTimeDate($infodata['work_day'], 8);
            $infodata['birthday_date'] = getTimeDate($infodata['birthday'], 8);
            $infodata['login_time'] = getTimeDate($infodata['login_time'], 9);//登陆时间
            if ($infodata['leave_day']) {
                //离职日期
                $infodata['leave_day_date'] = getTimeDate($infodata['leave_day'], 8);
            }
        } else {
            $infodata['work_day_date'] = getTimeDate($infodata['work_day'], 7);//入职时间
            $infodata['birthday_date'] = getTimeDate($infodata['birthday'], 7);//出生年月

            $infodata['login_time'] = getTimeDate($infodata['login_time'],12);//登陆时间
            if ($infodata['leave_day']) {
                $infodata['leave_day_date'] = getTimeDate($infodata['leave_day'], 7);
            }
        }
        $infodata['mangname'] = getinfo($infodata['update_id'], 'admin')['nickname'];//编辑者
        $infodata['sex'] = $this->getmanagelang($infodata['sex'], 1);//性别
        $infodata['langperson'] = $this->getmanagelang($infodata['language_id'], 2);//语言
        $infodata['status'] = $this->getmanagelang($infodata['status'], 3);//状态
        $infodata['marry'] = $this->getmanagelang($infodata['marry'], 4);//婚姻状态
        $infodata['education'] = $this->getmanagelang($infodata['education'], 5);//学历
        return $infodata;
    }

    //个人资料的查看(头部)
    public function getadminper()
    {
        $lang=is_lang();
        //获取个人的相关信息
        $uidname = session('admin');
        $uidname['langdata'] = array(
            '1' => lang("Chinese"),
            '2' => lang("English"),
            '3' => lang("Portuguese")
        );
        //权限设置的接口
        $rolewhere['mkey'] = 'position_' . $uidname['position_id'];
        $uidname['posnames'] = getlangname('multi_lang', $rolewhere, $lang);//职务名称

        $framewhere['mkey'] = 'department_' . $uidname['department_id'];
        $uidname['framnames'] = getlangname('multi_lang', $framewhere, $lang);//部门名称

        if ($lang != 'zh') {
            $uidname['birthday_date'] = getTimeDate($uidname['birthday'], 8);//出生年月
            $uidname['login_time'] = getTimeDate($uidname['login_time'], 9);//登陆时间
        } else {
            $uidname['birthday_date'] = getTimeDate($uidname['birthday'], 7);//出生年月
            $uidname['login_time'] = getTimeDate($uidname['login_time'],12);//登陆时间
        }
        $url='https://www.toolnb.com/Tools/Api/IP.html';
        $ardress=curlRequest($url,null)['data'];
        //通过登录ip获取登录地址
        $uidname['loginipaddress']=$ardress['country'].'/'.$ardress['cz_country'];
        $uidname['sex'] = $this->getmanagelang($uidname['sex'], 1);//性别
        $uidname['marry'] = $this->getmanagelang($uidname['marry'], 4);//婚姻状态
        $uidname['education'] = $this->getmanagelang($uidname['education'], 5);//学历
        return $uidname;
    }

    //头部个人资料提交
    public function means($data)
    {
        $adminid = $this->where('id', session('userid'))->setField('language_id', $data['language_id']);
        if ($adminid !== false) {
            return array('msg' => $data['nickname'] . lang("change_successful"), 'status' => 1);
        } else {
            return array('msg' => $data['nickname'] . lang("change_failed"), 'status' => 0);
        }
    }

    //处理语言标志的显示
    protected function getmanagelang($status, $code)
    {
        switch ($status) {
            case '1':
                $sex = lang("man");//男
                $lang = lang("Chinese");//中
                $status = lang("on_the_job");//状态
                $bachelordom = lang("married");//婚姻
                $education = lang("unknown");//学历
                break;
            case '2':
                $sex = lang("woman");//女
                $lang = lang("English");//英
                $status = lang("departure");//状态
                $bachelordom = lang("unmarried");//婚姻
                $education = lang("undergraduate");//学历
                break;
            case '3':
                $lang = lang("Portuguese");//葡
                $status = lang("locking");//状态
                $sex = $bachelordom = '';
                $education = lang("Master_degree");//学历
                break;
            case '4':
                $bachelordom = $status = $lang = $sex = '';
                $education = lang("Doctor");//学历
                break;
            case '5':
                $bachelordom = $status = $lang = $sex = '';
                $education = lang("college_degree");//学历
                break;
            case '6':
                $bachelordom = $status = $lang = $sex = '';
                $education = lang("technical_secondary_school");//学历
                break;
            case '7':
                $bachelordom = $status = $lang = $sex = '';
                $education = lang("below_high_school");//学历
                break;
            default:
                $education = $bachelordom = $status = $lang = $sex = '';
                break;
        }
        if ($code == 1) {
            return $sex;
        } elseif ($code == 2) {
            return $lang;
        } elseif ($code == 3) {
            return $status;
        } elseif ($code == 4) {
            return $bachelordom;
        } elseif ($code == 5) {
            return $education;
        }
    }

    //用户的添加与编辑的接口统计
    public function addeditadmin($data)
    {
        $ckdata = notEmpty(['name' => lang("account"), 'language_id' => lang("language"), 'nickname' => lang("nickname"), 'position_id' => lang("job"), 'work_day' => lang("entry_time"), 'wage' => lang("basic_salary"), 'birthday' => lang("brithday"), 'education' => lang("education"), 'department_id' => lang("department")]);
        if ($ckdata['status']==2) {
            return $ckdata;
        }
        $name = trim($data['name']);
        if (!$data['firstname'] || !$data['lastname']) {
            return array('msg' => lang("name_can't_be_empty"), 'status' => 2);
        }
        //账号
        if (!pregUser($name, 1, 20)) {
            return array('msg' => lang("account_format_error"), 'status' => 0);
        }
        //设置个人的权限
        if ($data['position_id']) {
            $data['auth_ids'] = Db::name('position')->where('id', $data['position_id'])->value('auth_ids');
        }
        $firstname = trim($data['firstname']);
        $lastname = trim($data['lastname']);
        if ($data['lang'] == 'zh') {
            $data['username'] = $firstname . $lastname;
        } else {
            $data['username'] = $lastname . ' ' . ' ' . $firstname;
        }
        $data['work_day'] = strtotime($data['work_day']);//入职时间
        $data['birthday'] = strtotime($data['birthday']);//出生年月
        unset($data['lang']);
        //判断编辑或者添加
        if ($data['act'] == 'personneladd') {
            $data['leave_day']=null;
            //查看账号是否被占用
            $infoma = $this->where(array('name' => $name))->find();
            if ($infoma) {
                return array('msg' => $name . lang("account_exists"), 'status' => 3);
            }
            //现在对用户填入的数据进行入库的操作
            unset($data['id']);
            $data['create_at'] = $data['update_at'] = time();
            $data['create_id'] = session('userid');
            $dpass = generatePassword();//随机密码
            $passsalt = encrypt_password($dpass);
            $data['passwd'] = $passsalt['password'];//密文
            $data['salt'] = $passsalt['salt'];//盐
            Db::startTrans();
            $adminid = $this->strict(false)->insertGetId($data);
            $data['admin_id'] = $adminid;
            $admininfoid = Db::name('admin_info')->strict(false)->insertGetId($data);
            if ($adminid && $admininfoid) {
                Db::commit();
                return array('status' => 1, 'msg' => $name . lang("added_successfully"), 'name' => $data['name'], 'passwd' => $dpass);
            } else {
                return array('status' => 0, 'msg' => $name . lang("add_failed"));
            }
        } elseif ($data['act'] == 'personneledit') {
            if ($data['leave_day']) {
                $data['leave_day'] = strtotime($data['leave_day']);//离职时间
            }else{
                $data['leave_day']=null;
            }
            $map['id'] = $data['id'];
            //判断状态
            $infostatus = $this->where($map)->find();
            if ($infostatus['status'] == 3) {
                return array('msg' => $name . lang("is_locked_and_can't_be_edited"), 'status' => 0);
            }
            //对数据进行编辑
            $adminupdate = array(
                'name' => $name,
                'nickname' => trim($data['nickname']),
                'department_id' => $data['department_id'],
                'position_id' => $data['position_id'],
                'language_id' => $data['language_id'],
                'update_id' => session('userid'),
                'update_at' => time(),
                'status' => $data['status'],
                'work_day' => $data['work_day'],
                'leave_day' => $data['leave_day'],
            );
            $admininfoupdate = array(
                'firstname' => trim($data['firstname']),
                'lastname' => trim($data['lastname']),
                'birthday' => $data['birthday'],
                'sex' => $data['sex'],
                'marry' => $data['marry'],
                'wage' => $data['wage'],
                'education' => $data['education'],
                'username' => $data['username'],
            );
            Db::startTrans();
            $resupadminid = $this->where($map)->update($adminupdate);
            $resadmininfoid = Db::name('admin_info')->where('admin_id', $data['id'])->update($admininfoupdate);
            if ($resupadminid !== false && $resadmininfoid !== false) {
                Db::commit();
                return array('status' => 1, 'msg' => $name . lang("edited_successfully"));
            } else {
                return array('status' => 0, 'msg' => $name . lang("edit_failed"));
            }
        }
    }

    //设置权限
    public function setroot($data)
    {
        if (!isset($data['auth_ids'])) {
            return array('msg' => lang("personal_permission_can't_be_empty"), 'status' => 2);
        }
        $auth_ids = $data['auth_ids'];
        //通过里面的id，判断最顶级的id是否写入
        $menupid = Db::name('menu')->where(['pid' => 0, 'disable' => 0])->select();
        foreach ($menupid as $menupidkey => $menupidval) {
            //获取顶级下的二级
            $idarr = array_column(Db::name('menu')->where(['pid' => $menupidval['id'], 'disable' => 0])->select(), 'id');
            $arrempty = array_intersect($idarr, $auth_ids);
            if (!empty($arrempty)) {
                array_push($auth_ids, $menupidval['id']);
            }
        }
        $auth_ids = implode(",", $auth_ids);
        $authids = $this->where('id', $data['id'])->setField('auth_ids', $auth_ids);
        if ($authids !== false) {
            return array('msg' => $data['nickname'] . lang("setting_permission_successfully"), 'status' => 1);
        } else {
            return array('msg' => $data['nickname'] . lang("failed_setting_permission"), 'status' => 0);
        }

    }

    //检测登录的时的判断
    public function getLoginStatu($name, $passwd, $verify)
    {
        if (!$name) {
            return array('msg' => lang("account_can't_be_empty"), 'status' => 2);
        }
        if (!$passwd) {
            return array('msg' => lang("password_can't_be_empty"), 'status' => 2);
        }
        if (!$name || !$passwd) {
            return array('msg' => lang("account_and_password_can't_be_empty"), 'status' => 2);
        }
        $info = $this->where(['name' => $name])->find();
        if (!$info) {
            $this->getcode(1);
            return array('msg' => lang("the_account_doesn't_exist"), 'status' => 3, 'count' => cookie('admin_cache'));
        } else {
            if ($info['status'] == 3) {
                $this->getcode(1);
                //判断锁定时间是否到达
                return array('msg' => lang("the_user_is_locked,_please_contact_the_administrator"), 'status' => 0);
            }
            $password = encrypt_password($passwd, $info['salt'])['password'];//加密的密文
            $login = $this->where(['name' => $name, 'passwd' => $password])->find();
            if (!$login) {
                $this->getcode(1);
                if ($verify) {
                    $this->getcode(2);
                    if (cookie('admin_lock') >= 3) {
                        //表示有验证码的输入依然错误3次，账号正确，密码错误，验证码正确,锁定用户
                        $this->where(['name' => $name])->setField('status', 3);
                    }
                } else {
                    return array('msg' => lang("account_or_password_incorrect"), 'status' => 0, 'count' => cookie('admin_cache'));
                }
            } else {
                $resdata['loginip'] = getIp();//登录的ip
                $resdata['login_time'] = time();//登录时间
                $this->where(['name' => $name, 'passwd' => $password])->update($resdata);//更新登录后的信息
                linkbankhandle(0);
                session('userid', $login['id']);//当前用户的did
                cookie('admin_cache', null);
                return array('msg' => lang("login_successful"), 'status' => 1);
            }
        }
    }

//处理验证码的相关的操作
    private function getcode($code)
    {
        if ($code == 1) {
            $admincode = cookie('admin_cache');
            if (!$admincode) {
                cookie('admin_cache', 1);
            } else {
                cookie('admin_cache', cookie('admin_cache') + 1);
            }
        } else {
            $adminlock = cookie('admin_lock');
            //锁定时间设置一小时
            if (!$adminlock) {
                cookie('admin_lock', 1);
            } else {
                cookie('admin_lock', cookie('admin_lock') + 1);
            }
        }
    }

//修改密码
    public function editpass($data)
    {
        $ckdata = notEmpty(['oldpass' => lang("current_password"), 'newpass' => lang("new_password"), 'confirm' => lang("confirm_password")]);
        if ($ckdata['status']==2) {
            return $ckdata;
        }
        //验证两次密码
        if ($data['newpass'] != $data['confirm']) {
            return array('msg' => lang("the_new_password_doesn't_match_the_cofirm_passward"), 'status' => 0);
        }
        //验证密码
        if (!pregPW($data['newpass'], 1, 20)) {
            return array('msg' => lang("password_format_doesn't_match"), 'status' => 0);
        }
        $uid = session('userid');
        $info = getinfo($uid, 'admin');
        //验证旧密码是否错误
        $oldpass = encrypt_password($data['oldpass'], $info['salt'])['password'];//旧
        $newpass = encrypt_password($data['newpass']);//新
        if (!$info) {
            return array('msg' => lang("server_error"), 'status' => 0);
        } else {
            if ($info['passwd'] != $oldpass) {
                return array('msg' => lang("the_current_password_is_wrong,_please_fill_in_again"), 'status' => 0);
            } else {
                //对用户的密码进行修改，并退出网站
                $updata['passwd'] = $newpass['password'];
                $updata['salt'] = $newpass['salt'];
                $updata['update_at'] = time();
                $res = $this->where('id', $uid)->update($updata);
                if (!$res) {
                    return array('status' => 0, 'msg' => lang("edit_failed"));
                } else {
                    return array('status' => 1, 'msg' => lang("edited_successfully"));
                }
            }
        }

    }

//重置密码
    public function resetadmin($data)
    {
        $map['id'] = $data['id'];
        $dpass = generatePassword();//随机密码
        $passsalt = encrypt_password($dpass);
        $update['passwd'] = $passsalt['password'];//密文
        $update['salt'] = $passsalt['salt'];//盐
        $this->where($map)->update($update);//更新数据库的密码
        return $dpass;
    }

//处理用户锁定 离职 复职
    public function lockleaveresume($data)
    {
        $ids = $data['id'];
        if ($ids) {
            //单独获取这个查询数据的状态
            $deldata = $this->field('status,create_at,nickname')->where("id in($ids)")->select();
            $arrstatus = array_column($deldata, 'status');
            $arrnickname = array_column($deldata, 'nickname');
            if (count($arrnickname) > 3) {
                $namenick = $arrnickname[0] . $arrnickname[1] . $arrnickname[2] . '...';
            } else {
                $namenick = implode(",", $arrnickname);
            }
        }
        if ($data['act'] == 'lock') {
            if (!$ids) {
                return array('msg' => lang("please,_select_a_user_to_lock"), 'status' => 3);
            } else {
                $update['status'] = 3;//锁定
                $ret = $this->where("id in($ids)")->update($update);
                $success = $namenick . lang("locked_successfully");
                $failed = $namenick . lang("lock_failed");
            }
        } elseif ($data['act'] == 'leave') {
            if (!$ids) {
                return array('msg' => lang("please,_select_a_user_to_resignation"), 'status' => 3);
            } else {
                if (in_array('3', $arrstatus)) {
                    return array('msg' => $namenick . lang("status_is_locked_and_can't_be_resign"), 'status' => 0);
                    exit;
                }
                $update['status'] = 2;//离职
                $ret = $this->where("id in($ids)")->update($update);
                $success = $namenick . lang("resignation_successfully");
                $failed = $namenick . lang("failed_resignation");
            }
        } elseif ($data['act'] == 'resume') {
            if (!$ids) {
                return array('msg' => lang("please,_select_a_user_to_reinstate"), 'status' => 3);
            } else {
                if (in_array('3', $arrstatus)) {
                    return array('msg' => $namenick . lang("status_is_locked_and_can't_be_reinstate"), 'status' => 0);
                    exit;
                }
                $update['status'] = 1;//在职
                $ret = $this->where("id in($ids)")->update($update);
                $success = $namenick . lang("reinstatement_successful");
                $failed = $namenick . lang("reinstatement_failure");
            }
        } elseif ($data['act'] == 'delete') {
            if (!$ids) {
                return array('msg' => lang("please_select_user_to_clear"), 'status' => 3);
            } else {
                $posarrids = array_column($this->field('position_id')->where("id in($ids)")->select(), 'position_id');//删除的职位id
                if (in_array(1, $posarrids)) {
                    return array('msg' => lang("administrator_can't_clear"), 'status' => 0);
                    exit;
                } else {
                    if (in_array('3', $arrstatus)) {
                        return array('msg' => $namenick . lang("status_is_locked_and_can't_be_cleared"), 'status' => 0);
                        exit;
                    }
                     foreach ($deldata as $arrtimekey => $arrtimeval) {
                         $one = time();
                         $two = $arrtimeval['create_at'] + 252288000;
                         if ($two > $one) {
                             return array('msg' => $namenick . lang("removal_time_isn't_within_standard"), 'status' => 0);
                             exit;
                         }
                     }
                    $ret = $this->where("id in($ids)")->delete();
                    $success = $namenick . lang("cleared_successfully");
                    $failed = $namenick . lang("clear_failed");
                }
            }
        } elseif ($data['act'] == 'unlock') {
            if (!$ids) {
                return array('msg' => lang("please_select_the_user_to_unlock"), 'status' => 3);
            } else {
                $update['status'] = 1;//解锁
                $ret = $this->where("id in($ids)")->update($update);
                $success = $namenick . lang("unlock_successful_");
                $failed = $namenick . lang("unlock_failed");
            }
        }
        if ($ret === false) {
            return array('status' => 0, 'msg' => $failed);
        } else {
            return array('status' => 1, 'msg' => $success);
        }
    }
}


